package me.yangteng.zhihudaily.component;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.List;

import me.yangteng.zhihudaily.R;
import me.yangteng.zhihudaily.activity.StoryDetailActivity;
import me.yangteng.zhihudaily.model.StoriesBean;

/**
 * Created by MorenYang on 2017/12/18.
 */

public class DailyNewsListAdapter extends BaseAdapter {

  private static final String TAG = "DailyNewsListAdapter";

  private Context context;
  private List<StoriesBean> newsList;

  public DailyNewsListAdapter(Context context, List<StoriesBean> newsList) {
    this.context = context;
    this.newsList = newsList;
  }

  @Override
  public int getCount() {
    return this.newsList.size();
  }

  @Override
  public Object getItem(int i) {
    return this.newsList.get(i);
  }

  @Override
  public long getItemId(int i) {
    return this.newsList.get(i).getId();
  }

  @Override
  public View getView(int i, View view, ViewGroup viewGroup) {
    ViewHolder viewHolder;
    if (view == null) {
      view = LayoutInflater.from(this.context).inflate(R.layout.news_list_item_layout, null);
      viewHolder = new ViewHolder();
      viewHolder.storyImage = view.findViewById(R.id.storyImage);
      viewHolder.storyTitle = view.findViewById(R.id.storyTitle);
      view.setTag(viewHolder);
    } else {
      viewHolder = (ViewHolder) view.getTag();
    }
    viewHolder.storyTitle.setText(newsList.get(i).getTitle());
    Picasso.with(view.getContext())
      .load(newsList.get(i).getImages().get(0))
      .into(viewHolder.storyImage);

    final String storyId = "" + this.getItemId(i);
    view.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        Intent intent = new Intent(context, StoryDetailActivity.class);
        intent.putExtra("storyId", storyId);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
      }
    });

    return view;
  }

  private static class ViewHolder {
    TextView storyTitle;
    ImageView storyImage;
  }
}
